<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
</head>

<body>
    <div>
        <button> 发送请求 </button>
        <button> 取消请求 </button>
    </div>
    <script>
        const btn = document.querySelectorAll('button')
        let cancel = null;
        btn[0].onclick = function () {
            if (cancel !== null) {
                cancel()
            }
            axios({
                method: 'GET',
                url: 'http://localhost:3000/posts',
                // 1.添加配置对象的一个属性
                cancelToken: new axios.CancelToken(function (e) {
                    cancel = e
                })
            }).then((res) => {
                console.log(res)
                cancel = null
            })
        }

        btn[1].onclick = function () {
            cancel()
        }
    </script>
</body>

</html>